// pages/mealshop/mealshop.js
const wxapi = require("../../utils/wxapi")
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    listOfData: [],
    autoPay: true,
    noCanBuyMeal: true,
    mealIndex: null,
    isPaySubmit: false
  },

  /**
   * 获取套餐内容
   */
  getMealList() {
    wxapi.getPackAges(4).then(res => {
      if (res.result === '200') {
        this.setData({
          listOfData: res.object,
          mealIndex: 0
        })
      } else {
        wx.showModal({
          title: '提示信息',
          content: res.messageInfo,
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
          }
        })
      }
    })
  },

  /**
   * 获取空间状态 判断是否可以购买增容空间
   */
  getUserSpace() {
    const bodyParams = {
      stk: app.globalData.userInfo.cardNo
    }
    wxapi.selectSpaceMsg(bodyParams).then(res => {
      if (res.status === 200) {
        res.data.expirtDate ? this.setData({
          noCanBuyMeal: false
        }) : this.setData({
          noCanBuyMeal: true
        })
      }
    })
  },

  /**
   * 选择套餐
   * @param {*} e 
   */
  mealItemChange(e) {
    const mealIndex = e.currentTarget.dataset.mealIndex;
    if (this.data.noCanBuyMeal && this.data.listOfData[mealIndex].validDay === 150) {
      wx.showModal({
        title: '提示信息',
        content: '您未购买存储空间或存储空间已过期。',
        showCancel: false
      })
      return false;
    }
    this.setData({
      mealIndex
    })
  },

  /**
   * 是否自动续费
   * @param {*} e 
   */
  checkboxChange(e) {
    const autoPay = this.data.autoPay;
    this.setData({
      autoPay: !autoPay
    })
  },

  /**
   * 确认支付
   */
  paySubmit() {
    if (this.data.mealIndex !== null) {
      wx.showLoading({
        title: '生成订单'
      })
      this.setData({
        isPaySubmit: true
      })
      // 支付
      const openId = wx.getStorageSync('openId');
      if (openId) {
        this.wxPay(openId);
      } else {
        wx.login({
          success: (res) => {
            if (res.code) {
              const jsCode = res.code;
              const headers = {
                'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
              }
              wxapi.getMiniOpenId({ jsCode }, headers).then(res => {
                if (res.code === 20000) {
                  if (res.data) {
                    wx.setStorageSync('openId', res.data);
                    this.wxPay(res.data);
                  } else {
                    wx.hideLoading()
                    this.setData({
                      isPaySubmit: false
                    })
                    wx.showToast({
                      title: '获取openId失败',
                      icon:'error'
                    })
                  }

                } else {
                  wx.hideLoading();
                  wx.showModal({
                    title: '提示信息',
                    content: res.message,
                    showCancel: false
                  })
                }
              })
            } else {
              wx.showToast({
                title: '登录失败',
                icon:'error',
                success: () => {
                  this.setData({
                    isPaySubmit: false
                  })
                  wx.switchTab({
                    url: '/pages/index/index',
                  })
                }
              })
            }
          },
        })
      }
    } else {
      wx.showModal({
        title: '提示信息',
        content: '请选择购买套餐。',
        showCancel: false
      })
    }
  },

  wxPay(openId) {
    const bodyParams = {
      transactionType: 1,
      productCode: 'NATIVE_PAY',
      cardNo: app.globalData.userInfo.cardNo,
      businessTypes: 'NUM_SPACE_VIP',
      openId,
      spaceVipResult: {
        gamePackageId: this.data.listOfData[this.data.mealIndex].packageId,
      },
      autoPayResult: {
        autoPay: this.data.autoPay ? 1 : 0,
      },
    };
    const headers = {
      Authorization: app.globalData.token
    }
    wxapi.wxMiniPayV3(bodyParams, headers).then(res => {
      wx.hideLoading();
      if (res.code === 20000) {
        wx.requestPayment({
          nonceStr: res.data.nonceStr,
          package: res.data.packageValue,
          paySign: res.data.paySign,
          signType: res.data.signType,
          timeStamp: res.data.timeStamp,
          success: (res) => {
            this.setData({
              isPaySubmit: false
            })
            wx.switchTab({
              url: '/pages/center/center',
            })
          },
          fail: (res) => {
            this.setData({
              isPaySubmit: false
            })
            if (res.errMsg.indexOf('fail cancel') !== -1) {
              wx.showToast({
                title: '交易取消',
                icon:'none'
              })
            } else {
              wx.showToast({
                title: '订单数据异常',
                icon:'error'
              })
            }
          }
        })
      } else if (res.code === 501) {
        this.setData({
          isPaySubmit: false
        })
        wx.showToast({
          title: '登录状态失效',
          icon:'none',
          success: () => {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (!app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    } else {
      this.getMealList();
      this.getUserSpace();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})